﻿using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TyMES.Model.Record;
using Newtonsoft.Json;
using WalkingTec.Mvvm.Core;

namespace TyMES.Services
{
    public class HttpService
    {
        private readonly IHttpClientFactory httpClientFactory;
        private readonly ILogger logger;
        private readonly IServiceScope serviceScope;
        private readonly WTMContext context;

        public HttpService(IHttpClientFactory httpClientFactory, ILogger<HttpService> _logger, IServiceScopeFactory serviceScopeFactory)
        {
            this.httpClientFactory = httpClientFactory;
            this.logger = _logger;
            this.serviceScope = serviceScopeFactory.CreateScope();
            var sp = this.serviceScope.ServiceProvider;
            this.context = sp.GetRequiredService<WTMContext>();
        }

        public async Task<string> GetDataAsync(string url)
        {
            var httpClient = httpClientFactory.CreateClient("TYMES");
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, url);
                var response = await httpClient.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    logger.LogError($"Request to {url} failed with status code {response.StatusCode}");
                    return "GetFail";
                }

                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException exception)
            {
                logger.LogError(exception, "Unhandled exception occurred!");
                throw;
            }
        }

        public async Task<string> PostDataAsync(string url, string data)
        {
            var httpClient = httpClientFactory.CreateClient("TYMES");
            try
            {
                var content = new StringContent(data, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await httpClient.PostAsync(url, content);
                if(response.StatusCode == System.Net.HttpStatusCode.OK)
                    return await response.Content.ReadAsStringAsync();
                if(response.StatusCode == System.Net.HttpStatusCode.BadGateway)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        HttpResponseMessage response2 = await httpClient.PostAsync(url, content);
                        if (response2.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            return await response2.Content.ReadAsStringAsync();
                        }
                        if (i == 1)
                        {
                            StationLogRecord record = new StationLogRecord();
                            record.LineCode = "502";
                            record.Date_Time = DateTime.Now;
                            record.CreateTime = DateTime.Now;
                            record.StationCode = GetErrorStationCode(data);
                            record.Log = "工厂mes返回异常" + url + data + response.StatusCode;
                            context.DC.Set<StationLogRecord>().Add(record);
                            await context.DC.SaveChangesAsync();
                        }
                    }
                }
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException exception)
            {
                logger.LogError(exception, "Unhandled exception occurred!");
                throw;
            }
        }

        public string GetErrorStationCode(string psd)
        {
            if(psd.IndexOf("\"stationCode\":\"")<0)
                return "502";
            int startindex = psd.IndexOf("\"stationCode\":\"") + "\"stationCode\":\"".Length;
            
            if(startindex > 0 && startindex + 10 <= psd.Length)
            {
                string stationCode = psd.Substring(startindex , 8);
                return stationCode;
            }
            return "502";
        }

    }
}
